﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Net.Mail;
using System.Timers;
using System.Security.Cryptography;

using MySql;
using MySql.Data;
using MySql.Data.MySqlClient;

using OpenPop.Mime;
using OpenPop.Mime.Header;
using OpenPop.Pop3;
using OpenPop.Pop3.Exceptions;
using OpenPop.Common.Logging;

using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.Configuration;
using System.Net;
using System.Collections.Specialized;
using System.Diagnostics;


namespace doris.Ticketuser
{
    public partial class newTicket3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            this.setDropDownMenu();

            MySqlCommand cmd;
            MySqlConnection con = new MySqlConnection(WebConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString);
            String CustID = Membership.GetUser().ProviderUserKey.ToString();
            String email = "";
            MySqlDataReader reader;
            cmd  = new MySqlCommand("SELECT UserID, Email FROM user", con);

            try
            {
                con.Open();
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    if (CustID == reader["UserID"].ToString())
                    {
                        email = reader["Email"].ToString();
                    }
                }
                Label2.Text = email;

            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
            finally
            {
                con.Close();
            }
        }
         
        //Set up the list for the DropDownMenu
        public void setDropDownMenu()
        {
            LinkedList<String> list = new LinkedList<String>();
            MySqlCommand cmd;
            MySqlConnection con = new MySqlConnection(WebConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString);
            MySqlDataReader reader;
            cmd  = new MySqlCommand("SELECT Service FROM service", con);

            try
            {
               
                con.Open();
                reader = cmd.ExecuteReader();

                while(reader.Read())
                {
                    list.AddLast(reader["Service"].ToString());                 
                }

                /*
                foreach(String l in list)
                {
                    Label5.Text = Label5.Text + l + " ";
                }
                 */

                DropDownList1.DataSource = list;
                DropDownList1.DataBind();

            }
            catch (MySqlException ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            finally
            {
                con.Close();
            }
        }

        public MAILConnection FetchSMTP()
        {
            MAILConnection smtp = new MAILConnection();
            MySqlConnection conn = new MySqlConnection(WebConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString);
            try
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;

                //          Console.WriteLine("Connecting to MySQL...");
                //                cmd.CommandText = "getTicketStatus";
                cmd.CommandText = "getEnabledSmtp";
                cmd.CommandType = CommandType.StoredProcedure;

                MySqlDataReader reader = cmd.ExecuteReader();

                if (reader.Read())
                {
                    smtp.ConnectionName = reader.GetValue(1).ToString();
                    smtp.Server = reader.GetValue(2).ToString();
                    smtp.UseCredentials = (int.Parse(reader.GetValue(3).ToString()) == 1 ? true : false);
                    smtp.Username = reader.GetValue(4).ToString();
                    smtp.Password = reader.GetValue(5).ToString();
                    smtp.Port = int.Parse(reader.GetValue(6).ToString());
                    smtp.UseSSL = (int.Parse(reader.GetValue(7).ToString()) == 1 ? true : false);
                    smtp.Enabled = (int.Parse(reader.GetValue(8).ToString()) == 1 ? true : false);
                }

                cmd.Dispose();
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                Console.WriteLine("Error " + ex.Number + " has occurred: " + ex.Message);
            }
            finally
            {
                conn.Close();
            }
            return smtp;
        }

        public class MAILConnection
        {
            public String ConnectionName { get; set; }
            public String Server { get; set; }
            public Boolean UseCredentials { get; set; }
            public String Username { get; set; }
            public String Password { get; set; }
            public int Port { get; set; }
            public Boolean UseSSL { get; set; }
            public Boolean Enabled { get; set; }
        }

        public class DorisUser
        {
            public String CustID { get; set; }
            public String Username { get; set; }
            public String Password { get; set; }
            public int Exists { get; set; }
        }

        public class TicketStatus
        {
            public int TicketID { get; set; }
            public String Service { get; set; }
            public String Priority { get; set; }
            public String Status { get; set; }
        }

        public int AddTicket(String customerid, String title, int ticketpriorityid, String message)
        {
            int TicketID = 0;
            MySqlConnection conn = new MySqlConnection(WebConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString);
            try
            {
                MySqlCommand cmd = new MySqlCommand();
                conn.Open();
                cmd.Connection = conn;

                //          Console.WriteLine("Connecting to MySQL...");
                cmd.CommandText = "addTicket";
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@in_title", title);
                cmd.Parameters["@in_title"].Direction = ParameterDirection.Input;

                cmd.Parameters.AddWithValue("@in_userid", customerid);
                cmd.Parameters["@in_userid"].Direction = ParameterDirection.Input;

                cmd.Parameters.AddWithValue("@in_ticketpriorityid", ticketpriorityid);
                cmd.Parameters["@in_ticketpriorityid"].Direction = ParameterDirection.Input;

                cmd.Parameters.AddWithValue("@in_message", message);
                cmd.Parameters["@in_message"].Direction = ParameterDirection.Input;

                cmd.Parameters.AddWithValue("@out_ticketid", MySqlDbType.Int32);
                cmd.Parameters["@out_ticketid"].Direction = ParameterDirection.Output;

                cmd.Parameters.AddWithValue("@out_ticketdataid", MySqlDbType.Int32);
                cmd.Parameters["@out_ticketdataid"].Direction = ParameterDirection.Output;

                cmd.ExecuteNonQuery();

                TicketID = int.Parse(cmd.Parameters["@out_ticketid"].Value.ToString());
                cmd.Dispose();
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                Console.WriteLine("Error " + ex.Number + " has occurred: " + ex.Message);
            }
            finally
            {
                conn.Close();
            }

            return TicketID;
        }

        public Boolean SendTicketResponse(String sender, String email, String subject, String fullname, String message)
        {
            MySqlConnection conn = new MySqlConnection(WebConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString);
            String Message = String.Empty;
            try
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;

                //          Console.WriteLine("Connecting to MySQL...");
                //                cmd.CommandText = "getTicketStatus";
                cmd.CommandText = "getDefaultResponse";
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add(new MySqlParameter("@out_message", MySqlDbType.Text));
                cmd.Parameters["@out_message"].Direction = ParameterDirection.Output;

                cmd.ExecuteNonQuery();

                Message = HttpUtility.HtmlDecode(cmd.Parameters["@out_message"].Value.ToString());
                cmd.Dispose();


            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                Console.WriteLine("Error " + ex.Number + " has occurred: " + ex.Message);
            }
            finally
            {
                conn.Close();
            }


            Message = Message.Replace("[fullname]", "Name LastName");
            //   Message = Message.Replace("[ticketid]", data.TicketID.ToString());
            Message = Message.Replace("[subject]", subject);
            //     Message = Message.Replace("[department]", data.Service);
            //     Message = Message.Replace("[priority]", data.Priority);
            //     Message = Message.Replace("[status]", data.Status);
            Message = Message.Replace("[url]", "URL");
            //      Message = Message.Replace("[username]", "");
            //      Message = Message.Replace("[password]", "");

            try
            {
                Debug.WriteLine("13243");
                string MyFrom = sender;
                Debug.WriteLine("51");
                string MyTo = email;
                Debug.WriteLine("41");
                string MyBody = Message;
                Debug.WriteLine("221");

                MAILConnection smtp = FetchSMTP();
                /*                string MySmtpMailServerName = "mail.broadpark.no";
                                int MySmtpMailServerPort = 25; //25 is the default for SMTP

                                SmtpClient MySmtpClient = new SmtpClient(MySmtpMailServerName, MySmtpMailServerPort);*/
                Debug.WriteLine("1111");
                SmtpClient MySmtpClient = new SmtpClient(smtp.Server, smtp.Port);
                Debug.WriteLine("111");
                if (smtp.UseCredentials)
                {
                    MySmtpClient.Credentials = new NetworkCredential(smtp.Username, smtp.Password);
                }
                Debug.WriteLine("11");
                if (smtp.UseSSL)
                {
                    MySmtpClient.EnableSsl = true;
                }

                Debug.WriteLine("Sender epost fra " + smtp.Server + ", " + smtp.Port + " identifisert med " + smtp.Username + " og " + smtp.Password);
                //                MySmtpClient.Send(MyFrom, MyTo, MySubject, MyBody);

                using (MailMessage newMail = new MailMessage())
                {

                 //   Debug.WriteLine("from: " + MyFrom + ", to: " + MyTo + ", body: " + MyBody);
                    newMail.From = new MailAddress(MyFrom);
                    newMail.To.Add(MyTo);
                    //       newMail.Subject = MySubject;
                    newMail.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(MyBody, null, "text/html"));
                    MySmtpClient.Send(newMail);
                }

                Debug.WriteLine("Message sent.");
            }
            catch (Exception MyError)
            {
                Debug.WriteLine("SendTicketResponse2");
                Console.WriteLine("An error has occurred: " + MyError.Message);
                return false;
            }
            Console.WriteLine("Done sending through smtp");
            return true;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {

            storeTicket();

            /*
            MySqlConnection con = new MySqlConnection(WebConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString);
            String CustID = Membership.GetUser().ProviderUserKey.ToString();
            MySqlDataReader reader;
            MySqlCommand cmd;
            String username;
            String email;
            String subject;
            String fullname = String.Empty;
            String message;
            TicketStatus data = new TicketStatus();
            int ticketpriorityid;
            String responder = "doris@mpdemo.no";

            cmd = new MySqlCommand("SELECT u.UserID, t.TicketID, Username FROM user u, ticket t WHERE t.userID = u.UserID", con);

            email = Label2.Text;
            subject = TextBox2.Text;
            fullname = "Fornavn Etternavn";
            message = Editor.Text;
            ticketpriorityid = 4;

            try
            {
                con.Open();
                reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    if (CustID == reader["UserID"].ToString())
                    {
                        username = reader["userName"].ToString();
                    }
                }
                Debug.WriteLine("SendTicketResponse");
                AddTicket(CustID, subject, ticketpriorityid, message);
                SendTicketResponse(responder, email, subject, fullname, message);

            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                Debug.WriteLine("Error " + ex.Number + " has occurred: " + ex.Message);
                // Label5.Text = ex.ToString();
            }
            Editor.Text = "";
            TextBox2.Text = "";
            Response.Redirect("ticketSentRespons.aspx");
             */
             
        }
       
        protected void Button2_Click(object sender, EventArgs e)
        {
            Response.Redirect("userMain.aspx");

        }

        protected void storeTicket()
        {
           
            MySqlConnection conn = new MySqlConnection(WebConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString);
            try
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;

                cmd.CommandText = "addTicket";
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add(new MySqlParameter("@in_title", MySqlDbType.VarChar));
                cmd.Parameters["@in_title"].Value = "A Ticket Title";
                cmd.Parameters["@in_title"].Direction = ParameterDirection.Input;

                cmd.Parameters.Add(new MySqlParameter("@in_userid", MySqlDbType.VarChar));
                cmd.Parameters["@in_userid"].Value = "d7954803-a894-4379-b9fc-bc39cfb8a43b"; //Session["UserID"];
                cmd.Parameters["@in_userid"].Direction = ParameterDirection.Input;

                cmd.Parameters.Add(new MySqlParameter("@in_ticketpriorityid", MySqlDbType.UInt32));
                cmd.Parameters["@in_ticketpriorityid"].Value = 1;
                cmd.Parameters["@in_ticketpriorityid"].Direction = ParameterDirection.Input;

                cmd.Parameters.Add(new MySqlParameter("@in_message", MySqlDbType.VarChar));
                cmd.Parameters["@in_message"].Value = Editor.Text;
                cmd.Parameters["@in_message"].Direction = ParameterDirection.Input;

                cmd.Parameters.Add(new MySqlParameter("@out_ticketid", MySqlDbType.Int32));
                cmd.Parameters["@out_ticketid"].Direction = ParameterDirection.Output;
                cmd.ExecuteNonQuery();
                
                int TicketID = int.Parse(cmd.Parameters["@out_ticketid"].Value.ToString());
                cmd.Dispose();
            }
            catch (MySql.Data.MySqlClient.MySqlException ex){
                Debug.WriteLine("Error " + ex.Number + " has occurred: " + ex.Message);
            }finally{
                conn.Close();
            }
        }
    
    }
}